<template>
  <view>
    <!-- #ifdef MP-WEIXIN -->
    <button open-type="getPhoneNumber" :plain="plain" :style="{border: plain ? 0 : '' }" :class="classname" @getphonenumber.stop="getPhoneNumber">{{ text }}</button>
    <!-- #endif -->

    <!-- #ifdef H5 -->
    <xr-popup ref="hgPopupLogin" type="center" :mask-click="false" class="phone-login">
      <view class="phone-login-wrap">
        <view class="close-me" @click="close"><view class="ic ic-close-big"/></view>
        <view class="phone-login" ref="msk">
          <view class="login-title">短信登录</view>
          <view class="login-text">登录后查看答案解析</view>
          <view class="login-phone">
            <input class="login-phone-input" type="number" v-model="phone" placeholder="输入手机号码" @blur="pageDown"/>
          </view>
          <view class="login-code">
            <input class="login-code-input" maxlength="4" type="number" v-model="code" placeholder="输入验证码" @blur="pageDown"/>
            <view class="login-code-but active" @click="getPhoneCode">
              {{ phoneCodeStatus ? phoneCodeCountTime : '获取验证码' }}
            </view>
          </view>
          <button class="login-but" @click="getLogin">登录</button>
        </view>
      </view>
    </xr-popup>
    <button type="button" :class="classname" @click="open">{{ text }}</button>
    <!-- #endif -->
  </view>
</template>
<script>
export default {
  name: 'GetPhoneNumber',
  props: {
    text: {
      type: String,
      default: ''
    },
    callback: {
      type: Boolean,
      default: false
    },
    classname: {
      type: String,
      default: 'xr-buy-bttuon'
    },
    plain: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      loading: false,
      phoneLogining: false,
      phone: '',
      code: '',
      phoneCodeCountTime: 60,
      phoneCodeStatus: false,
      phoneCodeTimer: null,
      phoneCodeSuccess: false
    }
  },
  mounted () {
    if (uni.flux.store.state.env.isH5Test) {
      this.phone = uni.getStorageSync('testMyPhone') || ''
    }
  },
  methods: {
    getPhoneNumber (event) {
      if (this.loading) {
        uni.showLoading({ title: '授权中' })
        return
      }
      this.loading = true
      uni.flux.track.PhoneAuthPopup()
      if (event.detail.errMsg === 'getPhoneNumber:ok') {
        this.$api.user.getPhoneNumber(event).then(() => {
          this.loading = false
          if (this.callback) {
            this.$emit('getPhoneNumberCallback')
          }

          // 只有book及下级页面调用
          if (uni.flux.utils.getCurrentPageFullPath().fullPath.includes('pages/book/')) {
            uni.flux.$api.user.updateBookInfo()
          }
          uni.showToast({ icon: 'none', title: '登录成功' })
          uni.flux.track.PhoneAuthSuccess()
        }).catch((res) => {
          uni.removeStorage({ key: uni.flux.config.tokenKey })
          this.loading = false
        })
      } else {
        uni.showToast({
          title: '授权失败，请重试',
          icon: 'none',
          duration: 2000
        })
        this.loading = false
      }
    },
    open () {
      this.$refs.hgPopupLogin.open()
      uni.flux.track.loginByPhone()
    },
    pageDown () {
      uni.pageScrollTo({
        scrollTop: 0, duration: 100
      })
    },
    close () {
      this.$refs.hgPopupLogin.close()
    },
    checkPhone () {
      const RegTel = /^(13[0-9]|14[01456879]|15[0-3,5-9]|16[2567]|17[0-8]|18[0-9]|19[0-3,5-9])\d{8}$/
      return RegTel.test(this.phone)
    },
    getPhoneCode () {
      if (!this.checkPhone()) {
        return uni.showToast({ icon: 'none', title: '手机号码不正确' })
      }
      if (this.phoneCodeStatus) return

      this.$api.user.getCode({
        phone: this.phone
      }).then(() => {
        uni.showToast({ icon: 'success', title: '验证码发送成功!' })
        this.phoneCodeStatus = true
        this.phoneCodeSuccess = true
        // 倒计时
        this.phoneCodeTimer = setInterval(() => {
          if (this.phoneCodeCountTime > 1) {
            this.phoneCodeCountTime--
          } else {
            clearInterval(this.phoneCodeTimer)
            this.phoneCodeTimer = null
            this.phoneCodeCountTime = 60
            this.phoneCodeSuccess = false
            this.phoneCodeStatus = false
          }
        }, 1000)
      }).catch((err) => {
        // 发送失败
        uni.showToast({ title: err, icon: 'none' })
        this.phoneCodeStatus = false
      })
    },
    getLogin () {
      if (!this.checkPhone()) {
        return uni.showToast({ icon: 'none', title: '手机号码不正确' })
      }
      if (!this.code) {
        return uni.showToast({ icon: 'none', title: '请输入短信验证码' })
      }
      this.$api.user.h5Login({
        phone: this.phone,
        code: this.code
      }).then((res) => {
        // @todo 顺序不能便
        this.close()
        if (res.token) {
          this.$store.commit('setToken', res.token)
        }
        if (res.reader) {
          this.$store.commit('setUserInfo', res.reader)
        }
        if (this.callback) {
          this.$emit('getPhoneNumberCallback')
        }
        const { route } = uni.flux.utils.getCurrentPageFullPath()
        if (route) {
          if (route.includes('/pages/book/')) {
            this.$api.user.updateBookInfo()
          }
          // 临时更新学习包状态
          if (route === '/pages/study-package/book/index/index') {
            this.$api.study.getStudyPackageInfo()
          }
        }
        uni.flux.track.loginSuccessByPhone()
        // 方便本地和test环境测试
        if (uni.flux.store.state.env.isH5Test) {
          uni.setStorage({ key: 'testMyPhone', data: this.phone })
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.phone-login-wrap {
  border-radius: 10px;
  background: #fff;
  .phone-login {
    z-index: 999;
    width: 290px;
    padding: 20px 22px;
  }

  .login-title {
    width: 140px;
    height: 35px;
    font-size: 20px;
    font-weight: 400;
    color: #333333;
    line-height: 35px;
  }

  .login-text {
    width: 144px;
    height: 22px;
    font-size: 16px;
    font-weight: 100;
    color: #333333;
    line-height: 22px;
  }

  .login-phone {
    height: 49px;
    margin-top: 15px;
    background: #F4F7FF;
    border-radius: 4px;
    border-width: 0;
    outline: none;

    .login-phone-input {
      padding: 12px;
    }
  }

  .login-code {
    position: relative;
    height: 49px;
    margin-top: 15px;
    background: #F4F7FF;
    border-radius: 4px;
    border-width: 0;
    outline: none;

    .login-code-input {
      padding: 13px;
    }

    .login-code-but {
      position: absolute;
      top: 0px;
      right: 0px;
      z-index: 999;
      width: 80px;
      height: 49px;
      padding-right: 22px;
      font-size: 13px;
      text-align: right;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #333333;
      line-height: 49px;
    }
  }

  .login-but {
    width: 100%;
    margin-top: 20px;
    margin-bottom: 10px;
    padding: 12px 14px;
    font-size: 18px;
    border-radius: 24px;
    color: #fff;
    background-color: #0091FF;
    line-height: 1;
    border-width: 0;
    outline: none;
  }
  .active {
    color: #0091FF !important;
  }

  .close-me {
    position: absolute;
    right: 24px;
    top: 20px;
    width: 20px;
    height: 20px;
    line-height: 20px;
    cursor: pointer;
    margin-bottom: 20px;
    text-align: right;
    .ic-close-big {
      color: #D8D9DC;
      font-size: 24px;
    }
  }

}
</style>
<style>
.xr-buy-bttuon {
  width: 130px;
  height: 46px;
  border-radius: 46rpx;
  font-size: 18px;
  font-weight: 600;
  color: #ffffff;
  line-height: 46px;
  text-align: center;
  background: linear-gradient(360deg, #FF9809 0%, #FFBF2F 100%);
  box-shadow: 0px 3px 3px 0px rgba(254, 138, 2, 0.4);
}
.mine-login-but{
  font-size: 16*2rpx;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #FFFFFF;
  line-height: 44rpx;
  padding: 14rpx 30rpx;
  margin-left: 12rpx;
  background: linear-gradient(270deg, #7AB7FF 0%, #4B8AFE 100%);
  border-radius: 39rpx;
}
.banner-login-btn {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 98;
  background-color:transparent;
  border: 0;
  outline: none;
  border-width: 0;
  box-shadow: none;
}
button:after {
  content: " ";
  width: 200%;
  height: 200%;
  position: absolute;
  top: 0;
  left: 0;
  border: 1px solid rgba(0,0,0,.0);
  -webkit-transform: scale(.5);
  transform: scale(.5);
  -webkit-transform-origin: 0 0;
  transform-origin: 0 0;
  box-sizing: border-box;
  border-radius: 10px;
}
.login-button{
  margin-top: 88rpx;
  height: 88rpx;
  background: #4989FF;
  border-radius: 88rpx;
  text-align: center;
  line-height: 88rpx;
  font-size: 36rpx;
  color: #fff;
}
.mine-active-login{
  height: 84rpx;
  width: 680rpx;
  outline: 0;
  border-radius: 44rpx;
  background: #FFC800;
  color: #fff;
  font-size: 32rpx;
  font-weight: 600;
}
.xr-study-button{
  width: 100%;
  height: 47px;
  line-height: 47px;
  color: #FFFFFF;
  font-weight: bold;
  background: #FF740F;
  box-shadow: 0px 6px 15px 0px #FDAC72;
  border-radius: 29px;
  text-align: center;
  box-sizing: border-box;
}
.login-analysis-buy-btn {
  width: 250px;
  height: 41px;
  line-height: 41px;
  border-radius: 25px;
  font-size: 32rpx;
  border: 1px solid #4989ff;
  color: #4989ff;
  text-align: center;
  background: #FFFFFF;
}
.study-member-button{
  width: 690rpx;
  height: 106rpx;
  margin: 44rpx 0;
  font-size: 36rpx;
  font-weight: 500;
  color: #421A00;
  line-height: 106rpx;
  text-align: center;
  background: linear-gradient(270deg, #E8BB6A 0%, #F4DFBA 100%);
  border-radius: 54rpx;
}
</style>
